import Session from './session.js';

export default {
    host: 'https://api.ali-fc.moapp.net.cn/service/stats',
    taskQueues: [],
    timer: null,
    appid: uni.getAccountInfoSync().miniProgram.appId,
    incr({group, field, uniqueKey, count=1}) {
        group = group || `weapp_${this.appid}`;
        this.taskQueues.push({
            group,
            field,
            unique_key: uniqueKey || Session.userInfo.unionid,
            count
        });

        this._send();
    },
    _send(retry=1) {
        if (this.timer) {
            clearTimeout(this.timer);
        }

        this.timer = setTimeout(() => {
            const sendData = [...this.taskQueues];
            this.taskQueues = [];
            uni.request({
                method: 'POST',
                url: `${this.host}/metrics/counter`,
                timeout: 2000,
                header: {
                    'Content-Type': 'application/json',
                    'X-Fc-Invocation-Type': 'Async'
                },
                data: sendData,
                complete: res => {
                    // 重要：发现uni.request的fail回调偶尔不会触发，所以这里用complete回调代替
                    this.timer = null;
                    if (res.statusCode >= 400) {
                        this.taskQueues.push(...sendData);
                        if (retry > 0) {
                            this._send(retry - 1);
                        }
                    }
                }
            });
        }, 3000);
    }
}